package com.tenton.servlet;

import com.tenton.pojo.Position;
import com.tenton.pojo.Province;
import com.tenton.pojo.User;
import com.tenton.service.Impl.PositionServiceImpl;
import com.tenton.service.Impl.ProvinceServiceImpl;
import com.tenton.service.Impl.UserServiceImpl;
import com.tenton.service.PositionService;
import com.tenton.service.ProvinceService;
import com.tenton.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;


@WebServlet(name = "InitServlet",
            urlPatterns = "/initServlet",
            loadOnStartup = 1)
public class InitServlet extends HttpServlet {

    @Override
    public void init() throws ServletException {
        //查询user表里面所有的数据
        UserService userService = new UserServiceImpl();
        List<User> userList = userService.listUser();

        //判断admin是否存在,存在的话就把flag的值设置为false，不执行添加操作
        boolean flag = true;
        for (User user : userList) {
            if(user.getUserName().equals("admin")){
                flag = false;
            }
        }
        Integer insertId = null;
        if(flag){
            //添加用户
            User admin = new User("admin","admin","BoZhi@123.com","四川","成都","看书");
            insertId = userService.insertUser(admin);
            //根据用户id添加职位
            PositionService positionService = new PositionServiceImpl();
            positionService.insertPosition(new Position(insertId,"admin"));
        }
    }

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //设置编码格式，防止乱码
        request.setCharacterEncoding("UTF-8");
        response.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        ProvinceService provinceService = new ProvinceServiceImpl();
        List<Province> provinceList = provinceService.listProvince();
        request.setAttribute("provinceList", provinceList);
        request.getRequestDispatcher("/regist.jsp").forward(request, response);
    }
}
